﻿#define _CRT_SECURE_NO_WARNINGS 1
#include"Stack.h"

// 初始化栈
void STInit(ST* ps)
{
	assert(ps);
	ps->top = NULL;
}
// 销毁栈
void STDestroy(ST* ps)
{
	assert(ps);
    stackNode* current = ps->top;
    while (current != NULL) 
    {
        stackNode* next = current->next;
        free(current);
        current = next;
    }
    ps->top = NULL;
}
// ⼊栈
//void STPush(ST* ps, STDataType x)
//{
//    assert(ps);
//    stackNode* newnode = (stackNode *)malloc(sizeof(stackNode));
//    if (newnode == NULL)
//    {
//        perror("malloc ");
//        return;
//    }
//    newnode->data = x;
//    newnode->next = NULL;
//    if (ps->top == NULL)
//    {
//        ps->top = newnode;
//    }
//    else
//    {
//        newnode->next = ps->top;
//        ps->top = newnode;
//    }
//}
// 


// 入栈操作
void STPush(ST* stack, int x) 
{
    stackNode* newNode = (stackNode*)malloc(sizeof(stackNode));
    if (newNode == NULL) {
        printf("内存分配失败\n");
        return;
    }
    newNode->data = x;
    newNode->next = stack->top;
    stack->top = newNode;
}

//出栈
void STPop(ST* ps)
{
    assert(ps);
    assert(!STEmpty(ps));

    if (ps->top->next == NULL)
    {
        free(ps->top);
        ps->top = NULL;
    }
    else
    {
        stackNode* next = ps->top->next;
        free(ps->top);
        ps->top = next;
    }
}
//取栈顶元素
STDataType STTop(ST* ps)
{
    assert(ps);
    assert(!STEmpty(ps));
    return ps->top->data;
}
//获取栈中有效元素个数
int STSize(ST* ps)
{
    assert(ps);
    stackNode* cur = ps->top;
    int count = 0;

    while (cur)
    {
        count++;
        cur = cur->next;
    }
    return count;
}
//栈是否为空
bool STEmpty(ST* ps)
{
    assert(ps);

    return ps->top == NULL;
}